package com.biglead.admin.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biglead.admin.mapper.AdminUserMapper;
import com.biglead.admin.mapper.UmsAdminRoleRelationDao;
import com.biglead.admin.mapper.UmsMenuMapper;
import com.biglead.admin.mapper.UserRoleRelationMapper;
import com.biglead.admin.param.UmsAdminParam;
import com.biglead.admin.pojo.UmsMenu;
import com.biglead.admin.pojo.UmsRole;
import com.biglead.admin.pojo.UserRoleRelation;
import com.biglead.admin.service.UmsAdminService;
import com.biglead.common.pojo.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 后台用户管理Service实现类
 * Created by macro on 2018/4/26.
 */
@Service("adminService")
public class UmsAdminServiceImpl extends ServiceImpl<AdminUserMapper, UserInfo> implements UmsAdminService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);

    @Autowired
    private UmsAdminRoleRelationDao umsAdminRoleRelationDao;

    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;

    @Override
    public List<UmsRole> getRoleList(Long adminId) {
        return umsAdminRoleRelationDao.getRoleList(adminId);
    }

    @Override
    public UserInfo queryById(Long userId) {
        return this.getById(userId);
    }

    @Override
    public Page<UserInfo> pageList(String keyword, Integer pageSize, Integer pageNum) {
        Page<UserInfo> page = Page.of(pageNum, pageSize);
        //queryWrapper组装查询where条件
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(keyword)) {
            //查询条件 name 模糊
            queryWrapper.like(UserInfo::getUsername, keyword);
        }
        //发起查询
        this.page(page, queryWrapper);
        return page;
    }

    @Override
    public boolean updateUserinfo(Long id, UserInfo admin) {
        UserInfo byId = this.getById(id);
        if (byId==null) {
            throw new RuntimeException("修改失败 用户不存在");
        }
        admin.setId(id);
        return this.updateById(admin);
    }

    @Override
    public UserInfo register(UmsAdminParam umsAdminParam) {
        String username = umsAdminParam.getUsername();
        String password = umsAdminParam.getPassword();
        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("请输入用户名");
        }
        if(StringUtils.isEmpty(password)){
            throw new RuntimeException("请输入密码");
        }


        UserInfo userInfo = new UserInfo();
        //拷贝属性数据
        BeanUtils.copyProperties(umsAdminParam, userInfo);
        userInfo.setCreateTime(new Date());
        userInfo.setStatus(1);
        //查询是否有相同用户名的用户
        long userCount = this.count(new QueryWrapper<UserInfo>().eq("username", username));
        if(userCount>0){
            throw new RuntimeException("已存在相同用户名的用户");
        }
        //将密码进行加密操作
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodePassword = bcryptPasswordEncoder.encode(password);
        userInfo.setPassword(encodePassword);
        //保存到数据库
        this.save(userInfo);


        return userInfo;
    }

    @Override
    public boolean deleteFromId(Long id) {
        if(id==null){
            return false;
        }

        return this.removeById(id);
    }

    @Override
    public boolean updateStatusFromId(Long id, Integer status) {
        if(id==null){
            return false;
        }
        UserInfo byId = this.getById(id);
        if (byId==null) {
            return false;
        }
        byId.setStatus(status);

        return   this.updateById(byId);
    }

    @Override
    public boolean updateUserRole(Long adminId, List<Long> roleIds) {
        if(roleIds==null || roleIds.size()==0){
            return false;
        }
        //先删除原来的关系
        userRoleRelationMapper.delete(new QueryWrapper<UserRoleRelation>().eq("admin_id",adminId));
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            for (Long roleId : roleIds) {
                UserRoleRelation roleRelation = new UserRoleRelation();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                userRoleRelationMapper.insert(roleRelation);
            }

        }
        return true;
    }

}
